package com.parsechina.hpush.broker.spi.persistence.h2;

import com.parsechina.hpush.broker.config.MqttConstants;
import com.parsechina.hpush.broker.internal.ClientInfo;
import com.parsechina.hpush.broker.internal.ClientStateEnum;
import com.parsechina.hpush.broker.spi.IClientStore;
import org.h2.mvstore.MVStore;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentMap;

/**
 * MapDB main persistence client info implementation
 *
 * @author lc
 * @since 2016/12/5
 */
public class H2ClientStore implements IClientStore {

    private final MVStore mvStore;

    private ConcurrentMap<String, ClientInfo> clientStore;

    H2ClientStore(MVStore mvStore) {
        this.mvStore = mvStore;
    }

    @Override
    public void sotreClient(ClientInfo clientInfo) {
        clientStore.put(clientInfo.getClientId(), clientInfo);
    }

    @Override
    public ClientInfo onlineState(String clientId) {
        ClientInfo clientInfo = clientStore.get(clientId);
        if (clientInfo == null) {
            return null;
        }
        clientInfo.setClientState(ClientStateEnum.ONLINE);
        return clientInfo;
    }

    @Override
    public ClientInfo offlineState(String clientId) {
        ClientInfo clientInfo = clientStore.get(clientId);
        if (clientInfo == null) {
            return null;
        }
        clientInfo.setClientState(ClientStateEnum.OFFLINE);
        return clientInfo;
    }

    @Override
    public ClientInfo getClient(String clientId) {
        return clientStore.get(clientId);
    }

    @Override
    public List<ClientInfo> getAllClients() {
        List<ClientInfo> clientInfos = new ArrayList<>();
        for (Map.Entry<String, ClientInfo> entry : clientStore.entrySet()) {
            clientInfos.add(entry.getValue());
        }
        return clientInfos;
    }

    @Override
    public void initStore() {

        clientStore = mvStore.openMap(MqttConstants.CACHE_CLIENT_INFO_KEY);
    }

}
